package com.dragon.web.commons.utils;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

import javax.imageio.ImageIO;

import com.marvels.common.utils.MarvelsLogUtil;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 
 * 图片的工具类
 * @author ljs
 *
 */
public class ImageUtils {
	
	public static void main(String[] args) {
		//File file = new File("C:/Users/IT/Desktop/big.png");
		File file = new File("D:/dev/tomcat7/wtpwebapps/fintech-api-web/upload/2017/3/4/big.png");
		
		//File file = new File("D:\\dev\\tomcat7\\wtpwebapps\\fintech-api-web\\upload/2017/3/4/idCard_1488592746105.png");
		thumbnailImage2(file,100, 100, "small_", false);
	}
	
	/**
	 * 把base64的图片字符串转换成图片
	 * @param imgStr
	 * @return
	 */
	@SuppressWarnings("restriction")
	public static void base64ToImg(String imgStr, File imgFile) {
		if (imgStr == null) { return;}
		if(!imgFile.getParentFile().exists()){
			imgFile.getParentFile().mkdirs();
		}
		BASE64Decoder decoder = new BASE64Decoder();
		OutputStream out = null;
		try {
			// Base64解码
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			out = new FileOutputStream(imgFile);
			out.write(b);
			out.flush();
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("=====ERROR=====", e);
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				MarvelsLogUtil.getInstance().error("=====ERROR=====", e);
			}
		}
	}
	
	
	/**
	 *  //图片转化成base64字符串  
	 *	//将图片文件转化为字节数组字符串，并对其进行Base64编码处理  
	 * @param imgFile
	 * @return
	 */
	
    @SuppressWarnings("restriction")
	public static String imageToBase64(String imgFile){
        InputStream in = null;  
        byte[] data = null;  
        //读取图片字节数组  
        try {  
            in = new FileInputStream(imgFile);          
            data = new byte[in.available()];  
            in.read(data);  
        } catch (IOException e){  
            MarvelsLogUtil.getInstance().error("=====ERROR=====", e);
        } finally {
        	try {
        		if(in != null){
					in.close();
        		}
			} catch (IOException e) {
				MarvelsLogUtil.getInstance().error("=====ERROR=====", e);
			}  
		}
        //对字节数组Base64编码  
        BASE64Encoder  encoder = new BASE64Encoder ();  
        return encoder.encode(data);//返回Base64编码过的字节数组字符串  
    }  
	
	/**
     * <p>Title: thumbnailImage</p>
     * <p>Description: 根据图片路径生成缩略图 </p>
     * @param imagePath    原图片路径
     * @param w            缩略图宽
     * @param h            缩略图高
     * @param prevfix    生成缩略图的前缀
     * @param force        是否强制按照宽高生成缩略图(如果为false，则生成最佳比例缩略图)
     */
    public static String thumbnailImage(File imgFile, int w, int h, String prevfix, boolean force ,String path){
        if(imgFile.exists()){
            try {
                String suffix = ".png";
                Image img = ImageIO.read(imgFile);
                if(!force){
                    // 根据原图与要求的缩略图比例，找到最合适的缩略图比例
                    int width = img.getWidth(null);
                    int height = img.getHeight(null);
                    if((width * 1.0) / w < (height * 1.0) / h){
                        if(width > w){
                            h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w / (width * 1.0)));
                            MarvelsLogUtil.getInstance().info("change image's height, width:{}, height:{}." + w + h);
                        }
                    } else {
                        if(height > h){
                            w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h/(height*1.0)));
                            MarvelsLogUtil.getInstance().info("change image's width, width:{}, height:{}." + w + h);
                        }
                    }
                }
                BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                Graphics g = bi.getGraphics();
                g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
                g.dispose();
                
                ImageIO.write(bi, suffix, new File("C:/Users/IT/Desktop/"));
                return path;
            } catch (IOException e) {
               MarvelsLogUtil.getInstance().error("generate thumbnail image failed.",e);
               return null;
            }
        }else{
            MarvelsLogUtil.getInstance().warn("the image is not exist.");
            return null;
        }
    }
	
    
    
    /**
     * <p>Title: thumbnailImage</p>
     * <p>Description: 根据图片路径生成缩略图 </p>
     * @param imagePath    原图片路径
     * @param w            缩略图宽
     * @param h            缩略图高
     * @param prevfix    生成缩略图的前缀
     * @param force        是否强制按照宽高生成缩略图(如果为false，则生成最佳比例缩略图)
     */
    public static void thumbnailImage2(File imgFile, int w, int h, String prevfix, boolean force){
        if(imgFile.exists()){
            try {
                // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
                String types = Arrays.toString(ImageIO.getReaderFormatNames());
                String suffix = "";
                // 获取图片后缀
                if(imgFile.getName().indexOf(".") > -1) {
                    suffix = imgFile.getName().substring(imgFile.getName().lastIndexOf(".") + 1);
                }// 类型和图片后缀全部小写，然后判断后缀是否合法
              /*  if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()) < 0){
                    return ;
                }*/
                Image img = ImageIO.read(imgFile);
                if(!force){
                    // 根据原图与要求的缩略图比例，找到最合适的缩略图比例
                    int width = img.getWidth(null);
                    int height = img.getHeight(null);
                    if((width*1.0)/w < (height*1.0)/h){
                        if(width > w){
                            h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w/(width*1.0)));
                        }
                    } else {
                        if(height > h){
                            w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h/(height*1.0)));
                        }
                    }
                }
                BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                Graphics g = bi.getGraphics();
                g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
                g.dispose();
                String p = imgFile.getPath();
                // 将图片保存在原目录并加上前缀
                ImageIO.write(bi, suffix, new File(p.substring(0,p.lastIndexOf(File.separator)) + File.separator + prevfix +imgFile.getName()));
            } catch (IOException e) {
            }
        }else{
            MarvelsLogUtil.getInstance().warn("the image is not exist.");
        }
    }
}
